<template>
  <div class="order-detail" v-loading="loading">
    <!-- 订单基本信息 -->
    <el-card class="order-info-card">
      <template #header>
        <div class="card-header">
          <span>订单信息</span>
          <el-tag :type="getStatusType(order.status)" size="large">
            {{ getStatusText(order.status) }}
          </el-tag>
        </div>
      </template>

      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单号">
          {{ order.order_number }}
        </el-descriptions-item>
        <el-descriptions-item label="下单时间">
          {{ formatDate(order.created_at) }}
        </el-descriptions-item>
        <el-descriptions-item label="订单金额">
          <span class="amount">¥{{ order.total_amount }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="支付状态">
          <el-tag :type="getPaymentStatusType(order.payment_status)">
            {{ getPaymentStatusText(order.payment_status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="支付方式">
          {{ order.payment_method || '未支付' }}
        </el-descriptions-item>
        <el-descriptions-item label="支付时间">
          {{ order.paid_at ? formatDate(order.paid_at) : '未支付' }}
        </el-descriptions-item>
        <el-descriptions-item label="完成时间">
          {{ order.completed_at ? formatDate(order.completed_at) : '未完成' }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 用户信息 -->
    <el-card class="user-info-card">
      <template #header>
        <div class="card-header">
          <span>用户信息</span>
        </div>
      </template>

      <el-descriptions :column="2" border>
        <el-descriptions-item label="用户姓名">
          {{ order.audience?.audience_name || '未知用户' }}
        </el-descriptions-item>
        <el-descriptions-item label="邮箱">
          {{ order.audience?.email || '无邮箱' }}
        </el-descriptions-item>
        <el-descriptions-item label="收货人">
          {{ order.recipient_name }}
        </el-descriptions-item>
        <el-descriptions-item label="联系电话">
          {{ order.recipient_phone }}
        </el-descriptions-item>
        <el-descriptions-item label="收货地址" :span="2">
          {{ order.shipping_address }}
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">
          {{ order.note || '无备注' }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 商品信息 -->
    <el-card class="products-card">
      <template #header>
        <div class="card-header">
          <span>商品信息</span>
          <span class="total-count">共 {{ order.items?.length || 0 }} 件商品</span>
        </div>
      </template>

      <el-table :data="order.items" style="width: 100%">
        <el-table-column label="商品" width="300">
          <template #default="{ row }">
            <div class="product-info">
              <el-image
                v-if="row.product?.cover_image"
                :src="getFullImageUrl(row.product.cover_image)"
                fit="cover"
                class="product-image"
              />
              <div class="product-details">
                <div class="product-name">{{ row.product_name }}</div>
                <div class="product-anchor" v-if="row.product?.anchor">
                  主播: {{ row.product.anchor.anchor_name }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="product_price" label="单价" width="120" align="center">
          <template #default="{ row }">
            ¥{{ row.product_price }}
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" width="100" align="center">
          <template #default="{ row }">
            ×{{ row.quantity }}
          </template>
        </el-table-column>
        <el-table-column prop="subtotal" label="小计" width="120" align="center">
          <template #default="{ row }">
            <span class="subtotal">¥{{ row.subtotal }}</span>
          </template>
        </el-table-column>
      </el-table>

      <div class="order-summary">
        <div class="summary-row">
          <span class="label">商品总价:</span>
          <span class="value">¥{{ order.total_amount }}</span>
        </div>
        <div class="summary-row total">
          <span class="label">订单总额:</span>
          <span class="value">¥{{ order.total_amount }}</span>
        </div>
      </div>
    </el-card>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button 
        v-if="order.status === 'paid'"
        @click="handleUpdateStatus('shipped')"
        type="success"
        size="large"
      >
        <el-icon><Truck /></el-icon>
        确认发货
      </el-button>
      <el-button 
        v-if="order.status === 'shipped'"
        @click="handleUpdateStatus('completed')"
        type="primary"
        size="large"
      >
        <el-icon><Check /></el-icon>
        确认完成
      </el-button>
      <el-button 
        v-if="['pending', 'paid'].includes(order.status)"
        @click="handleUpdateStatus('cancelled')"
        type="danger"
        size="large"
      >
        <el-icon><Close /></el-icon>
        取消订单
      </el-button>
      <el-button 
        @click="$emit('close')"
        size="large"
      >
        关闭
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Truck, Check, Close } from '@element-plus/icons-vue'
import { adminAPI } from '../../../api/admin'

interface Order {
  order_id: number
  order_number: string
  total_amount: number
  status: string
  payment_status: string
  payment_method?: string
  shipping_address: string
  recipient_name: string
  recipient_phone: string
  note?: string
  created_at: string
  paid_at?: string
  completed_at?: string
  audience?: {
    audience_name: string
    email: string
    phone?: string
  }
  items: OrderItem[]
}

interface OrderItem {
  order_item_id: number
  product_id: number
  product_name: string
  product_price: number
  quantity: number
  subtotal: number
  product?: {
    cover_image: string
    anchor?: {
      anchor_name: string
    }
  }
}

interface Props {
  order: Order
}

const props = defineProps<Props>()
const emit = defineEmits(['status-updated', 'close'])

const loading = ref(false)

// 更新订单状态
const handleUpdateStatus = async (newStatus: string) => {
  try {
    const actionText = getStatusActionText(newStatus)
    
    await ElMessageBox.confirm(
      `确定要将订单 "${props.order.order_number}" ${actionText}吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    loading.value = true
    
    const response = await adminAPI.updateOrderStatus(props.order.order_id, newStatus)
    
    let success, message
    
    if (response.success !== undefined) {
      success = response.success
      message = response.message
    } else if (response.data && response.data.success !== undefined) {
      success = response.data.success
      message = response.data.message
    } else {
      success = true
      message = '状态更新成功'
    }
    
    if (success) {
      ElMessage.success(`${actionText}成功`)
      emit('status-updated')
    } else {
      throw new Error(message || `${actionText}失败`)
    }
    
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('更新订单状态失败:', error)
      ElMessage.error('操作失败: ' + (error.message || '网络错误'))
    }
  } finally {
    loading.value = false
  }
}

// 工具函数
const getStatusType = (status: string) => {
  const types: { [key: string]: string } = {
    pending: 'warning',
    paid: '',
    shipped: 'info',
    completed: 'success',
    cancelled: 'danger',
    refunded: 'info'
  }
  return types[status] || ''
}

const getStatusText = (status: string) => {
  const texts: { [key: string]: string } = {
    pending: '待付款',
    paid: '已付款',
    shipped: '已发货',
    completed: '已完成',
    cancelled: '已取消',
    refunded: '已退款'
  }
  return texts[status] || status
}

const getPaymentStatusType = (status: string) => {
  const types: { [key: string]: string } = {
    pending: 'warning',
    paid: 'success',
    failed: 'danger',
    refunded: 'info'
  }
  return types[status] || ''
}

const getPaymentStatusText = (status: string) => {
  const texts: { [key: string]: string } = {
    pending: '待支付',
    paid: '已支付',
    failed: '支付失败',
    refunded: '已退款'
  }
  return texts[status] || status
}

const getStatusActionText = (status: string) => {
  const texts: { [key: string]: string } = {
    shipped: '发货',
    completed: '完成',
    cancelled: '取消'
  }
  return texts[status] || '操作'
}

const getFullImageUrl = (url: string) => {
  if (url.startsWith('http')) {
    return url
  }
  return `http://localhost:3000${url}`
}

const formatDate = (date: string | Date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}
</script>

<style scoped>
.order-detail {
  max-height: 80vh;
  overflow-y: auto;
}

.order-info-card,
.user-info-card,
.products-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-count {
  color: #909399;
  font-size: 14px;
}

.amount {
  font-weight: 600;
  color: #f56c6c;
  font-size: 16px;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 6px;
}

.product-details {
  flex: 1;
}

.product-name {
  font-weight: 500;
  margin-bottom: 4px;
  line-height: 1.4;
}

.product-anchor {
  font-size: 12px;
  color: #909399;
}

.subtotal {
  font-weight: 600;
  color: #f56c6c;
}

.order-summary {
  margin-top: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.summary-row.total {
  border-top: 1px solid #e4e7ed;
  padding-top: 8px;
  margin-top: 8px;
  font-size: 16px;
  font-weight: 600;
}

.summary-row.total .value {
  color: #f56c6c;
  font-size: 18px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 12px;
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}
</style>